package saleMarket.controller.basic;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import saleMarket.domain.Warehouse;
import saleMarket.service.WarehouseService;
import util.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @author 张方恒
 * @version 1.0  12-13-2020
 */

@Slf4j
@WebServlet("/warehouse.ctl")
public class WarehouseController extends HttpServlet {
    /**
     * 把一个或所有符合条件Warehouse对象以分页的形式响应到前端
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
    可能的请求
    {"id":1}
     */
    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException {
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        Object id_obj = request.getParameter("id");
        try {
            //如果id_Obj != null, 说明请求数据有id键，是请求某个Warehouse对象
            if (id_obj != null) {
                int id_int = Integer.parseInt(id_obj.toString());
                log.debug(""+id_int);
                responseWarehouse(id_int, response);
            } else {
                //响应多个仓库信息
                this.responseWarehouses(response);
            }
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            log.error(e.getMessage(),e);
            e.printStackTrace();
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
            //打印异常栈，方便调试（要用log4j代替）
            log.error(e.getMessage(),e);
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
            //打印异常栈，方便调试（要用log4j代替）
            log.error(e.getMessage(),e);
        }
    }

    //按分页信息响应符合条件的Warehouse对象和对象总数
    private void responseWarehouses(HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        //分页获得满足条件的所有Warehouse
        Collection<Warehouse> warehouses = WarehouseService.getInstance()
                .findAll();
        //第二个参数可以防止循环引用
        String warehouses_jsonStr = JSON.toJSONString(warehouses,
                SerializerFeature.DisableCircularReferenceDetect);

        //响应resp_jsonObj到前端
        response.getWriter().println(warehouses_jsonStr);
    }

    //响应一个Warehouse对象
    private void responseWarehouse(int id, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        Collection<Warehouse> warehouses =new ArrayList<>();
        //根据id查找仓库
        Warehouse warehouse = WarehouseService.getInstance().find(id);
        warehouses.add(warehouse);
        //第二个参数可以防止循环引用
        String warehouses_jsonStr = JSON.toJSONString(warehouses,
                SerializerFeature.DisableCircularReferenceDetect);
        //响应warehouse_json到前端
        response.getWriter().println(warehouses_jsonStr);
    }

    /**
     * POST, http://localhost:8080/warehousedepartment.ctl, 增加Warehouse
     * 增加一个Warehouse对象：将来自前端请求的JSON对象，增加到数据库表中
     *
     * @param request  请求对象
     * @param response 响应对象
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
            throws ServletException, IOException {
        //根据request对象，获得代表新增Warehouse的JSON字串
        String req_warehouseToAdd_jsonStr = JSONUtil.getJSON(request);
        //将JSON字串解析为Warehouse对象
        Warehouse warehouseToAdd = JSON.parseObject(req_warehouseToAdd_jsonStr,
                Warehouse.class);

        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        try {
            if(WarehouseService.getInstance().add(warehouseToAdd)){
                respMessage_jsonObj.put("message", "增加成功");
            }else{
                respMessage_jsonObj.put("message", "增加失败");
            }
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            //打印异常栈，方便调试（要用log4j代替）
            log.error(e.getMessage(),e);
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            //打印异常栈，方便调试（要用log4j代替）
            log.error(e.getMessage(),e);
        }
        //响应respMessage_jsonObj到前端
        response.getWriter().println(respMessage_jsonObj);
    }

    /**
     * DELETE, http://localhost:8080/warehouse.ctl?id=1, 删除id=1的Warehouse
     * 删除一个Warehouse对象：根据来自前端请求的id，删除数据库表中id的对应记录
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        Object id_obj = request.getParameter("id");
        int id_int = Integer.parseInt(id_obj.toString());
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        try {
            //到数据库表中删除对应的仓库
            if (WarehouseService.getInstance().delete(id_int)){
                respMessage_jsonObj.put("message", "删除成功");
            }else {
                respMessage_jsonObj.put("message", "删除失败");
            }
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        } catch (Exception e) {
            respMessage_jsonObj.put("message", e.getMessage());
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        }
        //响应respMessage_jsonObj到前端
        response.getWriter().println(respMessage_jsonObj);
    }


    /**
     * PUT, http://localhost:8080/warehouse.ctl, 修改Warehouse
     * <p>
     * 修改一个Warehouse对象：将来自前端请求的JSON对象，更新数据库表中相同id的记录
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String warehouseToUpdate_jsonStr = JSONUtil.getJSON(request);
        //将JSON字串解析为要修改的Warehouse对象（有id的完整对象）
        Warehouse warehouseToUpdate = JSON.parseObject(warehouseToUpdate_jsonStr, Warehouse.class);
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        try {
            if(WarehouseService.getInstance().update(warehouseToUpdate)){
                respMessage_jsonObj.put("message", "修改成功");
            }else {
                respMessage_jsonObj.put("message", "修改失败");
            }

        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            //打印异常栈，方便调试（要用log4j代替）
            log.error(e.getMessage(),e);
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            //打印异常栈，方便调试（要用log4j代替）
            log.error(e.getMessage(),e);
        }
        //响应respMessage_jsonObj到前端
        response.getWriter().println(respMessage_jsonObj);
    }

}
